package com.epalmpay.commom;

import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.mapper.BonusVerifyLogMapper;
import com.epalmpay.mapper.BonusVerifyRuleMapper;
import com.epalmpay.mapper.BonusVerifyShopMapper;
import com.epalmpay.service.trade.ITradeService;
import com.epalmpay.service.weixin.IWxApiMallService;
import com.epalmpay.service.withdraw.ITradeWithdrawService;
import com.epalmpay.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.mapper.ShopMapper;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.result.MerchQrcodeCallback;
import com.epalmpay.payplat.result.PayNotifyCallback;
import com.epalmpay.payplat.result.WithDrawCallback;
import com.epalmpay.service.app.IAppNoticeService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.IWxApiWalletService;
import com.epalmpay.service.yunstream.IOilcardOrderService;
import com.epalmpay.usercenter.UserAuthApi;
import com.epalmpay.util.Const;
import com.epalmpay.util.PageData;
import com.github.binarywang.wxpay.bean.WxPayOrderNotifyResponse;
import com.github.binarywang.wxpay.bean.result.WxPayOrderNotifyResult;

/**
 * 处理所有回调
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value="/payplat/callback")
public class PayplatNotifyController extends BaseController {


	private Logger logger = LoggerFactory.getLogger(PayplatNotifyController.class);
    
    @Resource
	private IWxApiWalletService wxApiWalletServiceService;
    @Resource
    private IWxApiMallService wxApiMallService;
	@Resource
	ITradeWithdrawService tradeWithdrawService;
	@Resource
	private IOilcardOrderService oilcardOrderService;
	@Resource
	private IMemberService memberService;

	@Resource
	private ITradeService tradeService;
	
	@Resource
	private IAppNoticeService appNoticeService;
	@Resource
	private ShopMapper shopMapper;

	@Resource
	private BonusVerifyRuleMapper bonusVerifyRuleMapper;

	@Resource
	private BonusVerifyLogMapper bonusVerifyLogMapper;

	@Resource
	private BonusVerifyShopMapper bonusVerifyShopMapper;
	
    /**
     * 提现成功的回调
     * @param request
     * @param GroupId
     * @param UserId
     * @param OrgOrderNum
     * @param OrderNum
     * @param transResult
     * @param StatusDesc
     * @param SignMsg
     * @param AccountType
     * @param TranAmt
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/withDrawNotify", produces={"application/xml;charset=UTF-8"})
    public String withDrawNotify(HttpServletRequest request, HttpServletResponse response,WithDrawCallback notify) throws Exception { 	
    	logger.info("=========================提现结果回调==========================================="); 
    	Enumeration enu=request.getParameterNames();  
    	while(enu.hasMoreElements()){  
    		String paraName=(String)enu.nextElement();  
    		logger.info(paraName+": "+request.getParameter(paraName));
    	}  
    	if(IPayAPI.checkWithDrawNotify(notify)){
    		String orgOrderNum=notify.getOrgOrderNum();
    		String transResult=	notify.getTransResult();
    		//以下具体的逻辑处理
    		//notifyf的里面数据都是已经进行解密后的数据可直接使用
			logger.info("提现结果回调"+transResult);
			logger.info("==================================订单号=================================="+orgOrderNum); 
				 if (orgOrderNum.startsWith(Const.APP_WITHDEAW)){//云流回调提现 
					 try {
							Boolean flag=wxApiWalletServiceService.updateWithDrawNotify(orgOrderNum,notify.getTransResult());
							if(flag){
								wxApiWalletServiceService.updatefinishSendMessage(orgOrderNum, UserAuthApi.MC_WITHDRAW);
							}
						} catch (Exception e) {
							e.printStackTrace(); 
							logger.info("======================云流提现回调失败======================================="); 
						}
				}else if(orgOrderNum.startsWith(Const.APP_REPAYMENT)){//云流信用卡还款回调提现
					try {
						Boolean flag=wxApiWalletServiceService.updateWithDrawNotify(orgOrderNum,notify.getTransResult());
						logger.info("…………………………………………………………"+flag); 
						if(flag){
							wxApiWalletServiceService.updatefinishSendMessage(orgOrderNum, UserAuthApi.MC_CREDTCARD_WITHDRAW);
						}
					} catch (Exception e) {
						e.printStackTrace(); 
						logger.info("======================云流信用卡还款回调失败======================================="); 
					}
			}else if(orgOrderNum.startsWith(Const.WX_WITHDEAW)){//微信提现回调
				//2.0其他提现回调--------------
				Boolean flag=wxApiWalletServiceService.updateWxWithDrawNotify(orgOrderNum,notify.getTransResult(),ROOT_HOME_URL);
				if(flag){
					logger.info("======================提现成功======================================="); 
				}
			}else if(orgOrderNum.startsWith(Const.PLATFORM_WITHDEAW)){//平台提现
					 //2.0其他提现回调--------------
						 Boolean flag=wxApiWalletServiceService.updateSySWithDrawNotify(orgOrderNum,notify.getTransResult());
						 if(flag){
								logger.info("======================平台提现成功======================================="); 
							}
			}
    	}
		return "0000";
	}
    
    
    
    /**
     * 微信公众号充值结果回调  包括微信消费支付  银行卡回调
     * @param request
     * @param notify
     * @return
     */
    @RequestMapping(value = "/rechargeNotify")
	public @ResponseBody String rechargeNotify(HttpServletRequest request, PayNotifyCallback notify) throws Exception{
    	logger.info("微信公众号充值结果回调  包括微信消费支付  银行卡回调");
    	Enumeration enu=request.getParameterNames();  
    	while(enu.hasMoreElements()){  
    		String paraName=(String)enu.nextElement();  
    		logger.info(paraName+": "+request.getParameter(paraName));  
    	}    
    	Boolean flag = false; 
    	if(IPayAPI.checkNotify(notify)){
    		logger.info("=====================================1==============================="+notify.getOrderNum()); 
    		logger.info("======================================2=============================="+notify.getOrgOrderNum()); 
    		logger.info("======================================3=============================="+notify.getTransResult()); 
    		String orgOrderNum = notify.getOrgOrderNum();
    		
			if (orgOrderNum.startsWith("ZSH") || orgOrderNum.startsWith("ZSY")) {
				// 表示油卡支付
				if(notify.getTransResult().equals("1")){
					TradeOffline tradeOffline=oilcardOrderService.oilCrdPayNotify(orgOrderNum,notify.getTransResult(),notify.getOrderNum());
					if(tradeOffline!=null){
						flag=true;
						//消费通知
						wxApiWalletServiceService.finishBuySendMessage(tradeOffline.getPayOrderid(),"油卡购买");
					}
				}
			}
			else if (orgOrderNum.startsWith("LF")){
				if(notify.getTransResult().equals("1")){
				//	Integer payAmt= SysUtils.Object2Integer(notify.getTranAmt());
					logger.info("=====================================流量购买回调==============================="); 
					TradeOffline tradeOffline=this.oilcardOrderService.finishFlowsPayNotify(notify.getOrderNum(),orgOrderNum);
					if(tradeOffline!=null){
						flag=true;
						//消费通知
						wxApiWalletServiceService.finishBuySendMessage(tradeOffline.getPayOrderid(),"流量购买");
					}
				}
			}else if (orgOrderNum.startsWith(Const.APP_RECHARGE)){
				     flag=wxApiWalletServiceService.updateAppRechargeOrderState(orgOrderNum,notify.getTransResult());
				    if(flag){
				    	logger.info("====app充值回调成功========="); 
						wxApiWalletServiceService.updatefinishSendMessage(orgOrderNum, UserAuthApi.MC_BLANCE_CHANGE);
				    }
			} else if (orgOrderNum.startsWith(Const.APP_CONSUME)) {
				    flag=wxApiWalletServiceService.updateGoodsOrderState(orgOrderNum, notify.getTransResult());
					if(flag){
						logger.info("====app消费回调成功=========");
						wxApiWalletServiceService.finishBuySendMessage(orgOrderNum, "商品购买");	
					}
			}
			else if (orgOrderNum.startsWith(Const.CONSUMPTION_VIRTUAL)) {
					flag=wxApiWalletServiceService.updateServiceGoodsOrderState(orgOrderNum, notify.getTransResult(),ROOT_HOME_URL);
							
			}
			else if (orgOrderNum.startsWith(Const.WECHAT_RECHAREG)) {
				 	wxApiWalletServiceService.updateRechargeOrderState(orgOrderNum,notify.getTransResult(),ROOT_HOME_URL);
			}
			else if (orgOrderNum.startsWith(Const.SEND_RECHARGE)) {
					flag=wxApiWalletServiceService.updateSendOrderState(orgOrderNum,notify.getTransResult(),ROOT_HOME_URL);
			}
			else if (orgOrderNum.startsWith(Const.CONSUMPTION_REAL)) {
					flag=wxApiWalletServiceService.updateMallGoodsOrderState(orgOrderNum,notify.getTransResult(),ROOT_HOME_URL);
			}
    	}
    	if(flag){
    		return "SUCCESS";
    	}else{
    		return null;
    	}
		
	}
    
    
    
    /**
     * 充值结果回调
     * @param request
     * @param notify
     * @return
     */
    @RequestMapping(value = "/merchQrcodeNotify")
	public @ResponseBody String merchQrcode(HttpServletRequest request, MerchQrcodeCallback notify) {
    	logger.info("===================================================================="); 
    	logger.info("/callback/merchQrcode");  
    	logger.info("回调");
    	Enumeration enu=request.getParameterNames();  
    	while(enu.hasMoreElements()){  
    		String paraName=(String)enu.nextElement();  
    		logger.info(paraName+": "+request.getParameter(paraName));  
    	}  
    	logger.info("===================================================================="); 
    	if(IPayAPI.checkMerchQrcodeNotify(notify)){
    		//以下具体的逻辑处理
    		//notifyf的里面数据都是已经进行解密后的数据可直接使用
    	}
		return "0000";
	}
    
   
	
	/**
	 * 微信原生充值回调
	 * @param request
	 * @param response
	 * @return （通知频率为15/15/30/180/1800/1800/1800/1800/3600，单位：秒） 返回xml
	 */
	@ResponseBody
	@RequestMapping(value = "/weixinpay", produces={"application/xml;charset=UTF-8"})
	public String payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception { 
		try {
			WxPayOrderNotifyResult result=wxApiWalletServiceService.WxPayResult(request);
			if(result!=null){
				String orderNo = result.getOutTradeNo();
				 if (orderNo.startsWith(Const.APP_RECHARGE)){
					 Boolean flag=wxApiWalletServiceService.updateOfflineWxPay(result);
							if(flag){
								logger.info("====app充值回调成功========="); 
								wxApiWalletServiceService.updatefinishSendMessage(orderNo, UserAuthApi.MC_BLANCE_CHANGE);
								return WxPayOrderNotifyResponse.success("处理成功!"); 
							}
					} else if (orderNo.startsWith(Const.APP_CONSUME)){
						Boolean flag=wxApiWalletServiceService.updateGoodsOfflineWxPay(result);
							if(flag){
								wxApiWalletServiceService.finishBuySendMessage(orderNo,"商品购买");
								return WxPayOrderNotifyResponse.success("处理成功!"); 
							}
						}
			}
		} catch (ApplicationException e1) {
			e1.printStackTrace();
		}
		return null; 
		
	}
	
	
   /** 程序执行完后必须打印输出“success”（不包含引号）。如果商户反馈给支付宝的字符不是success这7个字符，
    *  支付宝服务器会不断重发通知，直到超过24小时22分钟。一般情况下，25小时以内完成8次通知（通知的间隔频率一般是：4m,10m,10m,1h,2h,6h,15h; 
    *  https://docs.open.alipay.com/204/105301
    * @param request
    * @param response
    * @return
    * @throws Exception
    */
	//@RequestMapping("/alipaycharge")
	@ResponseBody
	@RequestMapping(value = "/alipaycharge", produces={"application/xml;charset=UTF-8"})
	public String alipaychargeNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		logger.info("=================================支付宝交易回调==================================="); 
		// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)
		// 商户订单号
		PageData pd = new PageData();
		pd = this.getPageData();
		logger.info("所有参数"+pd); 
		String out_trade_no = request.getParameter("out_trade_no");
		logger.info("=================================商户订单号==================================="+out_trade_no); 
		// 支付宝交易号
		String trade_no = request.getParameter("trade_no");
		logger.info("=================================支付宝交易号==================================="+trade_no); 
		// 交易状态
		String trade_status = request.getParameter("trade_status");
		// 交易金额
		String total_fee = request.getParameter("total_fee");
				//获取支付宝POST过来反馈信息
				HashMap<String, String> params = new HashMap<String, String>();
				Map requestParams = request.getParameterMap();
				for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
					String name = (String) iter.next();
					String[] values = (String[]) requestParams.get(name);
					String valueStr = "";
					for (int i = 0; i < values.length; i++) {
						valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
					}
					params.put(name, valueStr);
				}
				try {
					//验证签名
					if(wxApiWalletServiceService.verfyAliPay(params, out_trade_no)){
						logger.info("=================================签名验证通过==================================="); 
								if (out_trade_no.startsWith(Const.APP_RECHARGE)){//支付宝充值
									if (trade_status.equals("TRADE_SUCCESS")) {
										Boolean flag=wxApiWalletServiceService.updateOfflineAliPay(params,out_trade_no,true);
										//交易成功 消息回调
										if(flag){
											wxApiWalletServiceService.updatefinishSendMessage(out_trade_no, UserAuthApi.MC_BLANCE_CHANGE);
											return "success";
										}
									  }else{
										 wxApiWalletServiceService.updateOfflineAliPay(params,out_trade_no,false);
									  }
								} else if (out_trade_no.startsWith(Const.APP_CONSUME)){//支付宝消费
									if (trade_status.equals("TRADE_SUCCESS")) {
										Boolean flag=wxApiWalletServiceService.updateGoodsOfflineAliPay(params,out_trade_no,true);
										if(flag){
											wxApiWalletServiceService.finishBuySendMessage(out_trade_no,"商品购买");
											return "success";
										}
									  }
								}
					}
				} catch (Exception e) {
					e.printStackTrace(); 
					logger.info("=================================签名异常"); 
				}
		return null;
	}
	
	
	
	
	@RequestMapping(value = "/rechargeTkNotify")
	public @ResponseBody String rechargeTkNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
    	//{tradeTime=2017-08-07 15:30:05, businessCode=102900160914003, 
    	//orderNo=201708071530048668673, SignMsg=67C6C3470D2E43173D36128E0CEEA179, goodDedc=掌富测试（勿删）台卡收银, openid=o_UGbs5-8Ad0YCeu08NfqtFOHDOs,
    	//tradeStatus=1, remark=, order_type=WECHAT, outOrderNum=20170807153004RTQRREUR,
    	//url=http://weixin1.eboss007.com/pay/100020091219001/index.html?rid=15240, desc=您在商户（上海掌富网络技术有限公司)消费0.01元}
    	PageData pd = new PageData();
		pd = this.getPageData();
    	
		logger.info("微信公众号充值结果回调  包括微信消费支付  银行卡回调:"+pd);
		
		Boolean flag = false; 
		
		String orderNo=pd.getString("orderNo");
		String tradeStatus=pd.getString("tradeStatus");
		String orgOrderNum = pd.getString("outOrderNum");
			if (orgOrderNum.startsWith("ZSH") || orgOrderNum.startsWith("ZSY")) {
				// 表示油卡支付
				if(tradeStatus.equals("1")){
					TradeOffline tradeOffline=oilcardOrderService.oilCrdPayNotify(orgOrderNum,tradeStatus,orderNo);
					if(tradeOffline!=null){
						//消费通知
						wxApiWalletServiceService.finishBuySendMessage(tradeOffline.getPayOrderid(),"油卡购买");
					}
				}
			}
			else if (orgOrderNum.startsWith("LF")){
				if(tradeStatus.equals("1")){
					logger.info("=====================================流量购买回调==============================="); 
					TradeOffline tradeOffline=this.oilcardOrderService.finishFlowsPayNotify(orderNo,orgOrderNum);
					if(tradeOffline!=null){
						//消费通知
						wxApiWalletServiceService.finishBuySendMessage(tradeOffline.getPayOrderid(),"流量购买");
					}
				}
			}else if (orgOrderNum.startsWith(Const.APP_RECHARGE)){
				     flag=wxApiWalletServiceService.updateAppRechargeOrderState(orgOrderNum,tradeStatus);
				    if(flag){
				    	logger.info("====app充值回调成功========="); 
						wxApiWalletServiceService.updatefinishSendMessage(orgOrderNum, UserAuthApi.MC_BLANCE_CHANGE);
				    }
			} else if (orgOrderNum.startsWith(Const.APP_CONSUME)) {
				     flag=wxApiWalletServiceService.updateGoodsOrderState(orgOrderNum, tradeStatus);
					if(flag){
						logger.info("====app消费回调成功=========");
						wxApiWalletServiceService.finishBuySendMessage(orgOrderNum, "商品购买");	
					}
			}
			else if (orgOrderNum.startsWith(Const.CONSUMPTION_VIRTUAL)) {
					flag=wxApiWalletServiceService.updateServiceGoodsOrderState(orgOrderNum, tradeStatus,ROOT_HOME_URL);
							
			}
			else if (orgOrderNum.startsWith(Const.WECHAT_RECHAREG)) {
					flag=wxApiWalletServiceService.updateRechargeOrderState(orgOrderNum,tradeStatus,ROOT_HOME_URL);
			}
			else if (orgOrderNum.startsWith(Const.SEND_RECHARGE)) {
					flag=wxApiWalletServiceService.updateSendOrderState(orgOrderNum,tradeStatus,ROOT_HOME_URL);
			}
			else if (orgOrderNum.startsWith(Const.CONSUMPTION_REAL)) {
					flag=wxApiWalletServiceService.updateMallGoodsOrderState(orgOrderNum,tradeStatus,ROOT_HOME_URL);

					wxApiMallService.computeAmount(orgOrderNum);
			}
			//首单支付满
			TradeOffline tradeOffline = tradeService.selectByOrderId(orgOrderNum);

			if(tradeOffline != null) {
				logger.info("====首次消费送========");
				memberService.updateMemberFirstTradeSend(tradeOffline.getId(), tradeOffline.getPayerId(), tradeOffline.getGroupId(), tradeOffline.getRealAmount());
			}

			if(flag){
	    		return "SUCCESS";
	    	}else{
	    		return null;
	    	}
	}
	
	
	
	
	@RequestMapping(value = "/XDLTkNotify")
	public @ResponseBody String XDLTkNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
//		logNo.............201805090330528623
//		tradeNo.............201805094122574241
//		tradeStatus.............1
    	PageData pd = new PageData();
		pd = this.getPageData();
		logger.info("新大陆台卡回调:"+pd);
		
		String logNo=pd.getString("logNo");
		String tradeNo=pd.getString("tradeNo");
		String tradeStatus=pd.getString("tradeStatus"); 
		if (tradeNo.startsWith(Const.XDLTK_DEVICE)) {
					TradeOffline tradeOffline=wxApiWalletServiceService.updateTkOrderState(tradeNo,logNo,tradeStatus,ROOT_HOME_URL); 
					if(tradeOffline!=null){
						//只有transResult为1才表示支付成功发送通知,其他表示支付失败
			    		if(pd.getString("tradeStatus").equals("1")&&tradeOffline!=null){
							TradeOffline to = tradeService.selectByOrderId(tradeNo);
							if(to.getReceiverType() == 5) {//如果是商户商品，则进行推送
								//获取商户账号
								Userbase userbase = shopMapper.getUserNameByShopId(Long.parseLong(to.getReceiverId()));
								//发送退款推送信息
								Notice notice = new Notice();
								try {
									notice.setNoticetype(0);
									notice.setSender(to.getGroupId());
									notice.setReceiver(userbase.getUsername());
									notice.setNoticetitle("您有一笔退款申请");
									notice.setNoticetarget("ACCOUNT");
									notice.setNoticebody("您有一笔退款申请");
									notice.setGroupid(to.getGroupId());
									notice.setNoticestatus(1);
									notice.setIsplay(1);
									notice.setType(1);
									notice.setTvalue("");
									appNoticeService.sendNoticeToUsers(notice);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							logger.info( "回调成功");
			    		}else{
			    			logger.info( "回调修改失败");
			    		}
					}else{
						logger.info( "回调修改失败");
						
					}
			
		}
		
				
		return null;
	}
	
	
	
	

	/**
	 * 洗衣机支付回调方法
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/xyjRechargeTkNotify")
	public @ResponseBody String xyjRechargeTkNotify(HttpServletRequest request, HttpServletResponse response) throws Exception{
		//{tradeTime=2017-08-07 15:30:05, businessCode=102900160914003,
		//orderNo=201708071530048668673, SignMsg=67C6C3470D2E43173D36128E0CEEA179, goodDedc=掌富测试（勿删）台卡收银, openid=o_UGbs5-8Ad0YCeu08NfqtFOHDOs,
		//tradeStatus=1, remark=, order_type=WECHAT, outOrderNum=20170807153004RTQRREUR,
		//url=http://weixin1.eboss007.com/pay/100020091219001/index.html?rid=15240, desc=您在商户（上海掌富网络技术有限公司)消费0.01元}
		PageData pd = new PageData();
		pd = this.getPageData();

		logger.info("微信公众号洗衣机支付结果回调  包括微信消费支付  银行卡回调:"+pd);
		
		Boolean flag = false; 

		String orderNo=pd.getString("orderNo");
		String tradeStatus=pd.getString("tradeStatus");
		String orgOrderNum = pd.getString("outOrderNum");
		if (orgOrderNum.startsWith(Const.CONSUMPTION_VIRTUAL)) {
			 flag=wxApiWalletServiceService.updateServiceGoodsOrderState(orgOrderNum, tradeStatus,ROOT_HOME_URL);

		}
		else if (orgOrderNum.startsWith(Const.WECHAT_RECHAREG)) {
			 flag=wxApiWalletServiceService.updateRechargeOrderState(orgOrderNum,tradeStatus,ROOT_HOME_URL);
		}
		else if (orgOrderNum.startsWith(Const.SEND_RECHARGE)) {
			flag=wxApiWalletServiceService.updateSendOrderState(orgOrderNum,tradeStatus,ROOT_HOME_URL);
		}
		else if (orgOrderNum.startsWith(Const.CONSUMPTION_REAL)) {
			flag=wxApiWalletServiceService.updateMallGoodsOrderState(orgOrderNum,tradeStatus,ROOT_HOME_URL);
		}

		if(flag){
    		return "SUCCESS";
    	}else{
    		return null;
    	}
	}
	
	
}
